let express  =  require('express');
let router = express.Router();
let departmentDao = require('../../model/admin/department.js')

//渲染界面
router.get('/',async function (req,res) {
await res.render('department/department');   
})


//获取数据 
router.get('/list', async function(req,res){
    let  name = req.query.name || '';
    let page = req.query.page;
    let length = req.query.limit;
    let start =(page-1)*length;
    let departmentList  = await departmentDao.departmentList(start,length,name);
    let count =departmentList[1][0].sum;
    let data =departmentList[0]; 
    await res.json({code:0,count:count,data:data,msg:''})
})

//部门添加
router.post('/add',async function(req,res){
    let name = req.body.name;
    let director = req.body.director;
    let phone = req.body.phone;
    if(!name){
        return await res.json({status:203,msg:"请输入部门名称！"})
    };
    if(!director){
        return await res.json({status:203,msg:"请输入主管名！"})
    }
    if(!phone){
        return  await res.json({status:203,msg:"请输入负责人联系方式！"})
    }
    
    let validationDepartment  = await departmentDao.validationDepartment(name);
      if(validationDepartment.length>0){
        return await res.json({status:203,msg:"部门名称重复！"})
      }
     await departmentDao.addDepartment(name,director,phone);
     await res.json({status:200,msg:'success'});
})
//部门修改

router.post('/edit', async function(req,res){
let id = req.body.id;
let name = req.body.name;
let director = req.body.director;
let phone = req.body.phone;
if(!name){
    return await res.json({status:203,msg:"请输入部门名称！"})
};
if(!director){
    return await res.json({status:203,msg:"请输入主管名！"})
}
if(!phone){
    return  await res.json({status:203,msg:"请输入负责人联系方式！"})
}
let validationEditDepartment  = await departmentDao.validationEditDepartment(name);
      if(validationEditDepartment.length>0){
        return await res.json({status:203,msg:"部门名称重复！"})
      }
      await departmentDao.editDepartment(id,name,director,phone);
      await res.json({status:200,msg:'success'});

})
//删除部门

router.post('/del' ,async function(req,res){
let id = req.body.id;
await departmentDao.delDepartment(id);
await res.json({status:200,msg:'success'});

})



module.exports = router;